package cn.lijigou.shopping.service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cn.lijigou.shopping.HomeActivity;
import cn.lijigou.shopping.MainTabActivity;
import cn.lijigou.shopping.OrderDetailShopActivity;
import cn.lijigou.shopping.PushDetailShopActivity;
import cn.lijigou.shopping.R;
import cn.lijigou.shopping.ShoppingsActivity;
import cn.lijigou.shopping.domain.Advertising;
import cn.lijigou.shopping.domain.MResult;
import cn.lijigou.shopping.domain.Push;
import cn.lijigou.shopping.domain.Shop;
import cn.lijigou.shopping.util.APNManage;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.provider.Browser;
import android.util.Log;
import android.widget.Toast;

 
/**
* @author 黄明 E-mail:huangming@lookoo.cn
* @version CreatTime 2011-12-8  
* 类说�? 获取数据的服�?*/
public class LookooPushService extends Service {
	private TimerTask timerTask;
	private Context context;
	private SharedPreferences share ;
	private int  mDay;
	private Intent intents =null;
	private Push push ;
	private String pushCity;
	private String pushStatus;
	private int pushDate;
	private int id=100;
	private int tempdataType = 0;
	
    public LookooPushService() {
    	
    }
//    private HomeReceiver homeReceiverRegister;
	Handler mTimeoutHandler = new Handler() {
        public void handleMessage(Message msg) {
        	if(push!=null){
				String push_type = push.getPush_type();
				String title = push.getTitle();
				String content =  push.getContent();
				String link_url = push.getLink_url();
				push_type = push_type ;
				if(push_type.equals("1")){
					final String cid = link_url;
					int type;
					try{
						type=Integer.parseInt(cid);
						tempdataType=type;
					}catch (Exception e) {
						// TODO: handle exception
						e.printStackTrace();
						type=1;
						tempdataType = type;
					}
					intents = new Intent(context, MainTabActivity.class);   
					intents.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					intents.putExtra("pushType", tempdataType);
				}else if(push_type.equals("2")){
					final String cid = link_url;
					int type;
					try{
						type=Integer.parseInt(cid);
						tempdataType=type;
					}catch (Exception e) {
						// TODO: handle exception
						e.printStackTrace();
						type=1;
						tempdataType = type;
					}
					intents = new Intent(context, MainTabActivity.class);   
					intents.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					intents.putExtra("pushType", tempdataType);
				}else if(push_type.equals("3")){
						final String cid = link_url;
						intents = new Intent(context, PushDetailShopActivity.class);
						intents.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						intents.putExtra("shopid", link_url);   
//						context.startActivity(intent);
				}else if(push_type.equals("4")){
					
					intents =new Intent(Intent.ACTION_VIEW, Uri.parse(link_url));
				}
				id++;
				
				NotificationManager manager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
	    		Notification notification = new Notification(R.drawable.icon, title, 
						System.currentTimeMillis());
				notification.defaults = Notification.DEFAULT_SOUND|Notification.DEFAULT_VIBRATE;
				long[] vibrate = new long[] { 1000, 1000, 1000, 1000, 1000 }; 
				notification.vibrate = vibrate; 
				PendingIntent pendingIntent = PendingIntent.getActivity(context,
						id, intents, PendingIntent.FLAG_UPDATE_CURRENT);
				notification.setLatestEventInfo(context, title, content, pendingIntent);
				notification.flags |= Notification.FLAG_AUTO_CANCEL;
	        	manager.notify(100, notification); 	
        	}
        }
    };
@Override
public IBinder onBind(Intent intent) {
	// TODO Auto-generated method stub
	return null;
}
@Override
public void onCreate() {
	// TODO Auto-generated method stub
	super.onCreate();
}
@Override
public void onStart(Intent intent, int startId) {
	// TODO Auto-generated method stub
	super.onStart(intent, startId);
	context=this;
	share= context.getSharedPreferences("user", Context.MODE_PRIVATE);
	String action = intent.getAction();
	final Calendar c = Calendar.getInstance(); 
	mDay = c.get(Calendar.DAY_OF_MONTH);
	
	pushCity = share.getString("city", "北京");
	pushDate = share.getInt("pushDate", 0);
	pushStatus = share.getString("pushStatus", "1");
	if(mDay == pushDate){
		pushStatus = "0";
	}else if((mDay-pushDate) == 1){
		pushStatus = "0";
	}else if(pushDate == 0){
		pushStatus = "1";
	}else{
		pushStatus = "1";
	}
	APNManage aPNManage =new APNManage(this);
	timerTask = getPushTask(this);
	Timer timer=new Timer();
	timer.schedule(timerTask,0);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
	// TODO Auto-generated method stub
	return super.onStartCommand(intent, flags, startId);
}
 
private TimerTask getPushTask(final Context context) {
	TimerTask task=new TimerTask() {
		@Override
		public void run() {
				if(getNetConnectState(context)){
					push = new Push();
					String pushid = share.getString("pushid", "0");
					MResult result = ServerService.getPushData(push,pushCity,pushStatus,pushid);
					if(result!=null){
						if(result.isSuccess()){
							timerTask.cancel();
							mTimeoutHandler.sendEmptyMessage(1);
							Editor editor = share.edit();
							if((mDay-pushDate) != 1&&(mDay-pushDate) != 0){
								editor.putInt("pushDate",mDay);
							}
							editor.putString("pushStatus",pushStatus);
							editor.commit();
							editor.putString("pushid",push.getId());
							editor.commit();
						}
					}
			}else{
				timerTask.cancel();
			}
		}
	};
	return task;
}
	
	public boolean getNetConnectState(Context context) {
		boolean netConnect = false;
		ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		NetworkInfo infoM = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		if (info.isConnected() || infoM.isConnected()) {
			netConnect = true;
		}
		return netConnect;
	}
}
